<template>

  <div class="dashboard">
    <div class="header">
      <h1 style="font-size: 50px;">智慧果园数据可视化平台</h1>
    </div>
    
    <div class="content">
      <!-- 左栏：基本信息模块 -->
      <div class="left-panel">
        <div class="basic-info">
          <h3>基本信息</h3>
          <div class="info-item">
            <span>果蔬名称：</span>
            <span>{{ basicInfo.name }}</span>
          </div>
          <div class="info-item">
            <span>产地：</span>
            <span>{{ basicInfo.origin }}</span>
          </div>
          <div class="info-item">
            <span>品种：</span>
            <span>{{ basicInfo.variety }}</span>
          </div>
          <div class="info-item">
            <span>种植时间：</span>
            <span>{{ basicInfo.plantingDate }}</span>
          </div>
          <div class="info-item">
            <span>成熟度：</span>
            <span>{{ basicInfo.maturity }}%</span>
          </div>
        </div>
        
        <!-- 左下角：柱状图 -->
        <div class="bar-chart-container">
          <div ref="barChart" class="chart"></div>
        </div>
      </div>
      
      <!-- 中栏：地图区域 -->
      <div class="central-panel">
        <div id="main" class="map-container"></div>
      </div>
      
      <!-- 右栏：天气信息模块和扇形图 -->
      <div class="right-panel">
        <!-- 右上角：天气信息模块 -->
        <div class="weather-info">
          <div class="weather-item">
            <i class="icon-city"></i>
            <span>{{ weatherData.city }}</span>
          </div>
          <div class="weather-item">
            <i class="icon-temperature"></i>
            <span>{{ weatherData.currentTemperature }}°C</span>            <i class="icon-weather-description"></i>
            <span>{{ weatherData.currentWeatherDescription }}</span>
          </div>
          <!-- <div class="weather-item">

          </div> -->
          <div class="weather-item">
            <i class="icon-humidity"></i>
            <span>{{ weatherData.currentHumidity }}%RH</span>
          </div>
          <div class="weather-item">
            <i class="icon-wind"></i>
            <span>{{ weatherData.currentWindSpeed }} km/h</span>
          </div>
          
          <!-- 折线图容器 -->
          <div ref="lineChart" class="line-chart-container"></div>
        </div>
        
        <!-- 右下角：扇形图 -->
        <div class="pie-chart-container">
          <div ref="pieChart" class="chart"></div>
        </div>
      </div>
    </div>
  </div>

  <!-- 侧边栏弹窗 -->
  <div class="side-modal" v-if="showModal">
    <div class="modal-content">
      <button class="close-button" @click="closeModal">×</button>
      <h3>{{ currentCity }}果园详细信息</h3>
      <div class="farm-layout">
        <h4>果园厂房布局</h4>
        <div class="layout-image">
          <img :src="getLayoutImage(currentCity)" alt="果园布局图">
        </div>
      </div>
      <div class="camera-info">
        <h4>摄像头位置</h4>
        <ul>
          <li v-for="(camera, index) in cameraInfo" :key="index">
            {{ camera.name }} - {{ camera.position }} - 已识别 {{ camera.recognizedCount }} 个目标
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';
import { getCityData } from '../../mock/mock.js';

export default {
  name: 'Dashboard',
  data() {
    return {
      basicInfo: {
        name: '',
        origin: '',
        variety: '',
        plantingDate: '',
        maturity: 0
      },
      weatherData: {
        city: '',
        currentTemperature: 0,
        currentWeatherDescription: '',
        currentHumidity: 0,
        currentWindSpeed: 0,
        dailyForecasts: []
      },
      barChart: null,
      pieChart: null,
      lineChart: null,
      barData: [],
      pieData: [],
      mapChart: null,
      currentCity: '北京',
      cities: ['南宁市', '柳州市', '贵港市', '来宾市'], // 使用完整城市名称
      geoCoordMap: {
        '南宁市': [108.3267, 22.8108],
        '柳州市': [109.4121, 24.3150],
        '来宾市': [108.9976, 23.7283],
        '贵港市': [110.6244, 23.0884]
      },
      showModal: false, // 控制弹窗显示/隐藏
      cameraInfo: [], // 存储摄像头信息
      lastClickTime: 0, // 添加用于双击检测的时间变量
    };
  },
  mounted() {
    this.initCharts();
    this.fetchCityData();
    this.fetchWeatherData();
  },
  methods: {
    initCharts() {
      this.barChart = echarts.init(this.$refs.barChart);
      this.pieChart = echarts.init(this.$refs.pieChart);
      this.lineChart = echarts.init(this.$refs.lineChart);
      this.initMapChart();
    },
    setBarChart() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['湿度', '温度', '成熟度']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '数值',
            type: 'bar',
            data: this.barData
          }
        ]
      };
      this.barChart.setOption(option);
    },
    setPieChart() {
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '大小分布',
            type: 'pie',
            radius: '50%',
            data: this.pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.pieChart.setOption(option);
    },
    setLineChart() {
      const today = new Date();
      const dates = [];
      for (let i = 0; i < 7; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        dates.push(date);
      }

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates.map(date => 
            date.toLocaleDateString().replace(/\/\d+$/, '')
          )
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} °C'
          }
        },
        series: [
          {
            name: '最高温度',
            type: 'line',
            data: this.weatherData.dailyForecasts.map(item => item.maxTemperature),
            smooth: true,
            itemStyle: { color: '#ff7c7c' }
          },
          {
            name: '最低温度',
            type: 'line',
            data: this.weatherData.dailyForecasts.map(item => item.minTemperature),
            smooth: true,
            itemStyle: { color: '#7ca1ff' }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        }
      };
      this.lineChart.setOption(option);
    },
    fetchCityData(cityName = null) {
      getCityData(cityName)
        .then(response => {
          this.basicInfo = response.basicInfo;
          this.barData = response.barData;
          this.pieData = response.pieData;
          this.cameraInfo = response.cameraInfo; // 获取摄像头信息
          this.setBarChart();
          this.setPieChart();
        })
        .catch(error => {
          console.error('获取城市数据失败:', error);
        });
    },
    fetchWeatherData(city = null) {
      if (city && this.cities.includes(city)) {
        const today = new Date();
        const dailyForecasts = [];
        for (let i = 0; i < 7; i++) {
          const date = new Date(today);
          date.setDate(today.getDate() + i);
          dailyForecasts.push({
            date: date.toISOString().split('T')[0],
            maxTemperature: 30 + Math.floor(Math.random() * 5),
            minTemperature: 20 + Math.floor(Math.random() * 5),
            weatherCode: 0
          });
        }

        this.weatherData = {
          city: city,
          currentTemperature: 28 + Math.floor(Math.random() * 5),
          currentWeatherDescription: '晴天',
          currentHumidity: 60 + Math.floor(Math.random() * 20),
          currentWindSpeed: 5 + Math.floor(Math.random() * 10),
          dailyForecasts: dailyForecasts
        };

        this.$nextTick(() => {
          this.setLineChart();
        });
      } else {
        const today = new Date();
        const dailyForecasts = [];
        for (let i = 0; i < 7; i++) {
          const date = new Date(today);
          date.setDate(today.getDate() + i);
          dailyForecasts.push({
            date: date.toISOString().split('T')[0],
            maxTemperature: 25 + Math.floor(Math.random() * 5),
            minTemperature: 18 + Math.floor(Math.random() * 5),
            weatherCode: 0
          });
        }

        this.weatherData = {
          city: '北京',
          currentTemperature: 25,
          currentWeatherDescription: '晴天',
          currentHumidity: 69,
          currentWindSpeed: 8,
          dailyForecasts: dailyForecasts
        };

        this.$nextTick(() => {
          this.setLineChart();
        });
      }
    },
    initMapChart() {
      axios.get('https://geo.datav.aliyun.com/areas_v3/bound/450000_full.json')
        .then(response => {
          const geoJson = response.data;
          echarts.registerMap('guangxiMap', geoJson);
          
          this.mapChart = echarts.init(document.getElementById('main'));
          
          const option = {
            geo: {
              map: 'guangxiMap',
              roam: true,
              label: {
                emphasis: {
                  show: true
                }
              },
              itemStyle: {
                normal: {
                  areaColor: '#009245',
                  borderColor: '#fff'
                },
                emphasis: {
                  areaColor: '#f1c232'
                }
              }
            },
            series: [
              {
                type: 'map',
                map: 'guangxiMap',
                roam: true,
                label: {
                  show: true
                },
                itemStyle: {
                  areaColor: '#3498db',
                  borderColor: '#fff',
                  borderWidth: 1
                },
                data: [
                  { name: '南宁市', value: 1 },
                  { name: '柳州市', value: 2 },
                  { name: '来宾市', value: 3 },
                  { name: '贵港市', value: 4 }
                ]
              }
            ]
          };
          
          this.mapChart.setOption(option);
          
          // 地图点击事件处理
          this.mapChart.on('click', (params) => {
            const cityName = params.name;
            const shortCityName = cityName.replace('市', ''); // 移除“市”字进行匹配
            const cityList = ['南宁', '柳州', '贵港', '来宾'];
            if (cityList.includes(shortCityName)) {
              this.fetchCityData(shortCityName);
              this.fetchWeatherData(cityName);
            } else {
              alert(`没有在${cityName}发展`);
            }
          });

          // 地图双击事件处理（打开侧边栏）
          this.mapChart.on('dblclick', (params) => {
            const cityName = params.name;
            const shortCityName = cityName.replace('市', ''); // 移除“市”字进行匹配
            const cityList = ['南宁', '柳州', '贵港', '来宾'];
            if (cityList.includes(shortCityName)) {
              this.fetchCityData(shortCityName);
              this.fetchWeatherData(cityName);
              this.currentCity = cityName;
              this.showModal = true; // 显示弹窗
            } else {
              alert(`没有在${cityName}发展`);
            }
          });
        })
        .catch(error => {
          console.error('获取地图数据失败:', error);
        });
    },
    closeModal() {
      this.showModal = false;
    },
    getLayoutImage(cityName) {
  const cityImageMap = {
    '南宁市': '/src/public/无标题.png',
    '柳州市': '/src/public/无标题.png',
    '贵港市': '/src/public/无标题.png',
    '来宾市': '/src/public/无标题.png'
  };
  return cityImageMap[cityName] || '/src/public/无标题.png'; // 如果城市没有对应的图片，返回默认图片
}
  },
  watch: {
    barData: {
      handler() {
        if (this.barChart) {
          this.setBarChart();
        }
      },
      deep: true
    },
    pieData: {
      handler() {
        if (this.pieChart) {
          this.setPieChart();
        }
      },
      deep: true
    }
  },
  beforeUnmount() {
    if (this.barChart) {
      this.barChart.dispose();
    }
    if (this.pieChart) {
      this.pieChart.dispose();
    }
    if (this.lineChart) {
      this.lineChart.dispose();
    }
    if (this.mapChart) {
      this.mapChart.dispose();
    }
  }
};
</script>

<style scoped>
.dashboard {
  padding: 10px;
  background-color: #0a2a35;
  color: white;
  font-family: 'Arial', sans-serif;
  height: 800px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header {
  text-align: center;
  margin-bottom: 10px;
  padding: 5px;
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content {
  display: flex;
  flex-grow: 1;
  gap: 10px;
  overflow: hidden;
}

.left-panel, .central-panel {
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow: hidden;
  height: 800px;
}
.right-panel{
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow: hidden;
  height: 800px;
}
.left-panel {
  flex: 1;
}

.central-panel {
  flex: 2;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.right-panel {
  flex: 1;
}

.basic-info{
  background-color: rgba(0, 0, 0, 0.3);
  padding: 0px;
  border-radius: 4px;
  height: 400px;
  overflow: hidden;
}
.pie-chart-container {
  background-color: rgba(0, 0, 0, 0.3);
  padding: 0px;
  border-radius: 4px;
  height: 200px;
  overflow: hidden;
}
.bar-chart-container{
  background-color: rgba(0, 0, 0, 0.3);
  padding: 0px;
  border-radius: 4px;
  height: 600px;
  overflow: hidden;

}
.weather-info {
  background-color: rgba(0, 0, 0, 0.3);
  padding: 0px;
  border-radius: 4px;
  height: 350px;
  display: flex;
  flex-direction: column;
}

.weather-item {
  display: flex;
  align-items: center;
  height: 30px;
  margin-bottom: 5px;
}

.icon-temperature, .icon-humidity, .icon-wind, .icon-city {
  margin-right: 8px;
}

.chart {
  height: 400px;
  width: 100%;
}


.line-chart-container {
  position: absolute;
  top: 250px;
  left: 1300px;
   
  flex: 1;
  width: 350px;
   height: 250px;
}

.map-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

.pie-chart-container {
  height: 400px;
}

.info-item{
  padding: 0px;
  height: 20px;
}

/* 新增侧边栏弹窗样式 */
.side-modal {
  position: fixed;
  top: 0;
  right: 0;
  height: 100%;
  width: 350px;
  background-color: #e2f3fc;
  z-index: 100;
  transition: all 0.3s ease;
  transform: translateX(0);
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.3);
}

.close-button {
  position: absolute;
  top: 10px;
  right: 15px;
  background: #ff4d4f;
  color: white;
  border: none;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
}

.farm-layout {
  margin-bottom: 20px;
}

.layout-image img {
  width: 100%;
  height: auto;
  max-height: 200px;
  object-fit: contain;
}

.camera-info {
  margin-top: 15px;
}

.camera-info ul {
  list-style-type: none;
  padding-left: 10px;
}

.camera-info li::before {
  content: "●";
  color: #99ff00;
  display: inline-block;
  width: 1em;
  margin-left: -1em;
}
</style>